<script setup>
import { ref, onMounted, reactive } from 'vue'
import { getRoleListApi, passRoleApi, refuseRoleApi } from '@/api/role.js'
import { ElMessage, ElMessageBox } from 'element-plus'
let applyList = ref([])
let userRole = reactive({
  userId: '',
  roleId: ''
})

const getList = async () => {
  let result = await getRoleListApi()
  applyList.value = result.data
}

const pass = async row => {
  ElMessageBox.confirm('确定要通过该用户的申请吗', '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'success'
  }).then(async () => {
    userRole.roleId = row.roleId
    userRole.userId = row.userId
    await passRoleApi(userRole)
    ElMessage.success('操作成功')
    await getList()
  })
}

const refuse = async row => {
  ElMessageBox.confirm('确定要拒绝该用户的申请吗', '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    userRole.roleId = row.roleId
    userRole.userId = row.userId
    await refuseRoleApi(userRole)
    ElMessage.success('操作成功')
    await getList()
  })
}

// 角色格式化函数
const roleFormatter = row => {
  if (row.roleId === 1) {
    return '管理员'
  } else if (row.roleId === 3) {
    return '学生'
  } else {
    return '教师'
  }
}

onMounted(() => {
  getList()
})
</script>

<template>
  <el-main>
    <!-- 表格 -->
    <el-table
      default-expand-all
      :data="applyList"
      row-key="id"
      style="width: 100%"
    >
      <el-table-column prop="username" label="申请人" min-width="12%" />
      <el-table-column
        prop="roleId"
        :formatter="roleFormatter"
        label="申请角色"
        min-width="12%"
      />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button
            link
            type="success"
            icon="Edit"
            size="small"
            @click="pass(scope.row)"
            >同意</el-button
          >
          <el-button
            link
            type="danger"
            icon="Delete"
            size="small"
            @click="refuse(scope.row)"
            >拒绝</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </el-main>
</template>

<style scoped></style>
